package com.example.ourradio;

import java.io.IOException;
import java.io.InputStream;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.os.AsyncTask;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;

import com.example.ourradio.Feed.FeedItem;

public class DownloadJsonTask extends AsyncTask<String, Void, Feed> {
	
	private FeedFragment.OnFragmentInteractionListener mListener;
	private AbsListView mListView;
	private ListAdapter mAdapter;
	private Activity mActivity;
	private FeedTab mTab;
		
	public DownloadJsonTask(
		FeedFragment.OnFragmentInteractionListener listener,
		AbsListView listView,
		ListAdapter adapter,
		Activity activity,
		FeedTab tab
	) {
		mListener = listener;
		mListView = listView;
		mAdapter = adapter;
		mActivity = activity;
		mTab = tab;
	}
	
    @Override
    protected Feed doInBackground(String ... urls) {
        try {
            return loadJsonFromNetwork(urls[0]);
        } catch (IOException e) {
         	e.printStackTrace();
  			return new Feed();
        } catch (XmlPullParserException e) {
          	e.printStackTrace();
  			return new Feed();
        }
    }

    @Override
    protected void onPostExecute(Feed feed) {
    	if (null != mListener) {
			mListener.onLoadCompletion(feed, mTab);
		}  
       
    	mAdapter = new ArrayAdapter<FeedItem>(
    		mActivity,
    		android.R.layout.simple_list_item_1, android.R.id.text1,
    		feed.mItems);
    	((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);          
    }

    // Uploads JSON feed, parses it, and combines it with HTML markup. 
    // Returns HTML string.
    private Feed loadJsonFromNetwork(String urlString) 
    	throws XmlPullParserException, IOException {
    	InputStream stream = null;
    	// Creating JSON Parser instance
    	JSONParser jParser = new JSONParser();
    	JSONObject json = null;
    	
    	// Checks whether the user set the preference to include summary text
    	// SharedPreferences sharedPrefs = 
    	// 		PreferenceManager.getDefaultSharedPreferences(this);
    	// boolean pref = sharedPrefs.getBoolean("summaryPref", false);

    	Feed feed = new Feed();
      
    	try {
    		json = jParser.getJSONFromUrl(urlString);
    	// Makes sure that the InputStream is closed after the app is
    	// finished using it.
    	} finally {
    		if (stream != null) {
    			stream.close();
    		}
    	}

    	try {
    		feed.mTitle = json.getString("title");
    		feed.mLink = json.getString("link");
      	
    		JSONArray episodes = json.getJSONArray("episodes");
      	
    		feed.mItems = new FeedItem[episodes.length()];
    		// looping through All Episodes
    		for(int i = 0; i < episodes.length(); i++){
    			JSONObject episode = episodes.getJSONObject(i);
              
    			// Storing each json item in variable
    			feed.mItems[i] = feed.new FeedItem();
    			feed.mItems[i].mTitle = episode.getString("title");
    			feed.mItems[i].mLink = episode.getString("link");
    			feed.mItems[i].mSummary = episode.getString("summary");
    			feed.mItems[i].mKey = episode.getString("key");
    			if (episode.has("speechlink")) {
    				feed.mItems[i].mSpeechLink = 
    					episode.getString("speechlink");
    			}
   			
    		}
    	} catch (JSONException e) {
    		e.printStackTrace();
    	}
    
    	return feed;
    }
}
